package com.yunshang.shoppingmall.shopping.WeChat.service.impl;

import com.yunshang.shoppingmall.entity.User;
import com.yunshang.shoppingmall.entity.UserNo;
import com.yunshang.shoppingmall.service.SysUserNoService;
import com.yunshang.shoppingmall.shopping.WeChat.common.WeiXinSignUtil;
import com.yunshang.shoppingmall.shopping.WeChat.common.WeixinMessageInfo;
import com.yunshang.shoppingmall.shopping.WeChat.common.WeixinMessageModelUtil;
import com.yunshang.shoppingmall.shopping.WeChat.common.WeixinMessageUtil;
import com.yunshang.shoppingmall.shopping.WeChat.entity.TextMessage;
import com.yunshang.shoppingmall.shopping.WeChat.service.WeixinCoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * <p>Company: B505信息技术研究所 </p>
 * @Description: 微信消息处理核心service实现类
 * @Create Date: 2017年10月10日下午3:33:16
 * @Version: V1.00
 * @Author: 来日可期
 */
@Service("weixinCoreService")
public class WeixinCoreServiceImpl implements WeixinCoreService {

    private static Logger logger = LoggerFactory.getLogger(WeixinCoreServiceImpl.class);

    @Autowired
    private WeixinMessageUtil weixinMessageUtil;
    @Autowired
    private WeixinMessageInfo weixinMessageInfo;
    @Autowired
    private WeixinMessageModelUtil weixinMessageModelUtil;

    @Autowired
    private WeiXinSignUtil weixinSignUtil;

    @Autowired
    SysUserNoService sysUserNoService;

    @Override
    public String weixinMessageHandelCoreService(HttpServletRequest request,HttpServletResponse response) {


        if (request.getMethod().equals("GET")) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            if (signature != null && !signature.equals("")) {
                System.out.println("signature:" + signature);
                System.out.println("-------------验证微信服务号信息开始----------");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");

                logger.info("signature is :" + signature + "timestamp is" + timestamp + "nonce is :" + nonce);
                if (weixinSignUtil.checkSignature(signature, timestamp, nonce)) {
                    System.out.println("-----------验证微信服务号结束------------");
                    return echostr;
                } else {

                    // 此处可以实现其他逻辑
                    logger.warn("不是微信服务器发过来的请求，请小心！");
                    return null;
                }
            }
            return null;
        } else {
            System.out.println("开始接收数据!!");

            logger.info("------------微信消息开始处理-------------");
            // 返回给微信服务器的消息,默认为null

            String respMessage = null;

            try {

                // 默认返回的文本消息内容
                String respContent = null;
                // xml分析
                // 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
                Map<String, String> map = weixinMessageUtil.parseXml(request);
                // 发送方账号
                String fromUserName = map.get("FromUserName");
                weixinMessageInfo.setFromUserName(fromUserName);
                System.out.println("fromUserName--->" + fromUserName);
                // 接受方账号（公众号）
                String toUserName = map.get("ToUserName");
                weixinMessageInfo.setToUserName(toUserName);
                System.out.println("toUserName----->" + toUserName);
                // 消息类型
                String msgType = map.get("MsgType");
                weixinMessageInfo.setMessageType(msgType);
                logger.info("fromUserName is:" + fromUserName + " toUserName is:" + toUserName + " msgType is:" + msgType);

                // 默认回复文本消息
                TextMessage textMessage = new TextMessage();
                textMessage.setToUserName(fromUserName);
                textMessage.setFromUserName(toUserName);
                textMessage.setCreateTime(new Date().getTime());
                textMessage.setMsgType(weixinMessageUtil.RESP_MESSAGE_TYPE_TEXT);
                textMessage.setFuncFlag(0);

                // 分析用户发送的消息类型，并作出相应的处理

                // 文本消息
                if (msgType.equals(weixinMessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
//                respContent = "亲，这是文本消息！";
//                textMessage.setContent(respContent);
//                respMessage = weixinMessageUtil.textMessageToXml(textMessage);

//                    //String content = map.get("Content");
//
//                    if (content.equals("二维码")) {
//                        //respContent = "二维码";
//                        //textMessage.setContent(respContent);
//                        //respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                    } else if (content.equals("图文")) {
//                        //respMessage = weixinMessageModelUtil.followResponseMessageModel(weixinMessageInfo);
//                    } else {
//                        //respContent = "亲，这是文本消息！";
//                        //textMessage.setContent(respContent);
//                        //respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                    }
                }

//                // 图片消息
//                else if (msgType.equals(weixinMessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
//                    respContent = "您发送的是图片消息！";
//                    textMessage.setContent(respContent);
//                    respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                }
//
//                // 链接消息
//                else if (msgType.equals(weixinMessageUtil.REQ_MESSAGE_TYPE_LINK)) {
//                    respContent = "您发送的是链接消息！";
//                    textMessage.setContent(respContent);
//                    respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                }

                // 事件推送(当用户主动点击菜单，或者扫面二维码等事件)
                else if (msgType.equals(weixinMessageUtil.REQ_MESSAGE_TYPE_EVENT)) {

                    // 事件类型
                    String eventType = map.get("Event");
                    System.out.println("eventType------>" + eventType);
                    // 关注
                    if (eventType.equals(weixinMessageUtil.EVENT_TYPE_SUBSCRIBE)) {

//                        try {
//                            String EventKey = map.get("EventKey");
//                            String recommend = EventKey.replace("qrscene_X", "");
//
//                            System.out.println("recommend:" + recommend);
//
//                            //查询是否存在openid
//                            UserNo userNo1 = sysUserNoService.selectUserNoByOpenid(fromUserName);
//                            if (userNo1 == null) {
//                                //添加一条信息到用户编号表
//                                UserNo userNo = new UserNo();
//                                userNo.setRecommend(Integer.parseInt(recommend));
//                                userNo.setOpenid(fromUserName);
//                                userNo.setGhid(toUserName);
//                                userNo.setRank(19);
//                                int id = sysUserNoService.insertSelective(userNo);
//                                System.out.println("id:" + id);
//                            } else {
//                                System.out.println("id:已经存在");
//                            }
//                        } catch (Exception ex) {
//                            System.out.println(ex.getMessage());
//                        }

                        respMessage = weixinMessageModelUtil.followResponseMessageModel(weixinMessageInfo);
                    }
//                    // 取消关注
//                    else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
//                        respContent = "抱歉，没有很好的为你服务，欢迎下次关注!!";
//                        textMessage.setContent(respContent);
//                        respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                        //weixinMessageModelUtil.cancelAttention(fromUserName);
//                    }
//                    // 扫描带参数二维码
//                    else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_SCAN)) {
//                        respContent = "欢迎您回家!!";
//                        textMessage.setContent(respContent);
//                        respMessage = weixinMessageUtil.textMessageToXml(textMessage);
//                    }
//                    // 上报地理位置
//                    else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_LOCATION)) {
//                        System.out.println("上报地理位置");
//                    }
//                    // 自定义菜单（点击菜单拉取消息）
//                    else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_CLICK)) {
//
//                        // 事件KEY值，与创建自定义菜单时指定的KEY值对应
//                        String eventKey = map.get("EventKey");
//                        System.out.println("eventKey------->" + eventKey);
//
//                    }
//                    // 自定义菜单（(自定义菜单URl视图)）
//                    else if (eventType.equals(weixinMessageUtil.EVENT_TYPE_VIEW)) {
//                        System.out.println("处理自定义菜单URI视图");
//                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("系统出错");
                System.err.println("系统出错");
                respMessage = null;
            } finally {
                if (null == respMessage) {
                    respMessage = weixinMessageModelUtil.systemErrorResponseMessageModel(weixinMessageInfo);
                }
            }

            return respMessage;
        }
    }

}